package com.cb.domain.service.system.impl;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cb.common.menu.Menu;
import com.cb.core.Constants;
import com.cb.core.dao.GenericDAO;
import com.cb.core.service.impl.GenericManagerImpl;
import com.cb.core.webapp.paging.PagingBean;
import com.cb.domain.dao.system.AppResourceDAO;
import com.cb.domain.model.system.AppResource;
import com.cb.domain.service.system.AppResourceManager;

@Service
public class AppResourceManagerImpl extends GenericManagerImpl<AppResource, Long> implements AppResourceManager{
	
	@Autowired
	public AppResourceManagerImpl(AppResourceDAO appResourceDAO) {
		super(appResourceDAO);
	}

	@Autowired
	private AppResourceDAO appResourceDAO;
	
	/**
	 * {@inheritDoc}
	 */
	public List<AppResource>getByVo(AppResource vo,PagingBean pb){
		return appResourceDAO.getByVo(vo, pb);
	}
	
	/**
	 * {@inheritDoc}
	 */
	public void doSynchMenu(Collection <Menu> menus){
		
		Iterator<Menu> it=menus.iterator();
		while(it.hasNext()){
			Menu menu=it.next();
			
			AppResource resource=appResourceDAO.getByResourceName(menu.getName());
			if(resource==null){
				resource=new AppResource();
			}
			
			resource.setResourceName(menu.getName());
			resource.setResourceUrl(menu.getPattern());
			resource.setResourceDesc(menu.getDescription());
			resource.setResourceTitle(menu.getTitle());
			resource.setParentId(Constants.ROOT_RESOURCE_PK);
			resource.setPath(Constants.ROOT_RESOURCE_PK.toString());
			
			appResourceDAO.save(resource);
			
			if(menu.getItems()!=null && menu.getItems().size()>0){
				synchMenuItem(menu.getItems(),resource);
			}
		}
	}
	
	private void synchMenuItem(List<Menu> menuItems,AppResource parentResource){
		for(int i=0;i<menuItems.size();i++){
			Menu item=menuItems.get(i);
			
			AppResource resource=appResourceDAO.getByResourceName(item.getName());
			if(resource==null){
				resource=new AppResource();
			}
			resource.setResourceName(item.getName());
			resource.setResourceUrl(item.getPattern());
			resource.setResourceDesc(item.getDescription());
			resource.setResourceTitle(item.getTitle());
			resource.setParentId(parentResource.getResourceId());
			resource.setPath(parentResource.getPath()+"."+parentResource.getResourceId());
			appResourceDAO.save(resource);
			
			if(item.getItems()!=null && item.getItems().size()>0){
				synchMenuItem(item.getItems(),resource);
			}
		}
	}
	
	public List getByParentId(Long parentId){
		return appResourceDAO.getByParentId(parentId);
	}
	
}
